var utils = require("./utils");

utils.exitIfRepeat();

var width = device.width;
var height = device.height;

// 淘宝搜索界面商品列表id
var list_recycler = "com.taobao.taobao:id/libsf_srp_header_list_recycler";
//日志窗口高度
var logHeight = height/5;

var w = floaty.rawWindow(
    <card bg="#80000000">
        <vertical align="center">
            <text text="─ 当前脚本运行日志 ─" textSize="15" color="#FFFFFF" textStyle="bold" gravity="center" margin="0 0 0 5"/>
            <text id="WZ" text="" textSize="15" color="#FFFFFF" marginLeft="10" gravity="left"/>
        </vertical>
    </card>
);    
w.setSize(width, logHeight);
w.setTouchable(false);
w.setPosition(0, height - logHeight);

// 开启开关
var window = floaty.rawWindow(
    <frame bg="#00000000" align="center">
       <Switch id="switch" checked="true" gravity="center" textStyle="bold"/>
    </frame>
);
window.setSize(-2, -2);
window.setPosition(0, height - logHeight);

//关闭脚本按钮
var closeWindow = floaty.rawWindow(
    <linear bg="#00000000" layout_gravity="right">
        <text id="closeBtn" gravity= "center" text="关闭" textSize="14sp" textColor="white" padding="4 0"/>
    </linear>
);
closeWindow.setSize(-2, -2);
closeWindow.setPosition(9*width/10,height - logHeight);

closeWindow.closeBtn.on("click", function() {
    toastLog("停止了脚本");
    exit();
});

toastLog("等待无障碍权限开启……\n您必须手动授予本软件无障碍权限\n否则本软件将无法工作！");
auto.waitFor();
toastLog("无障碍权限已开启" + "\n" + "继续运行脚本……");

var descActivityName = "com.taobao.android.detail.wrapper.activity.DetailActivity";
var searchActivityName = "com.taobao.search.sf.MainSearchResultActivity";

//主宝贝浏览时长
var mainMins;
//其他宝贝浏览时长
var otherSecs;
//货比宝贝数量
var otherSize;

//总浏览数
var total;

//当前第几个
var cur = 0;

//搜索页滚动高度
var scrollHeight = 0;

function finish(){
    ui.run(function(){
        window.switch.checked = false;
        cur = 0;
        toastLog("完成当前任务！！！！");
        toastLog("点击开关重新开启！！！！");
    })
}

//监听start事件
events.on("start", (config) =>{
    mainMins = config.mainMins;
    otherSecs = config.otherSecs;
    otherSize = config.otherSize;
    total = parseInt(otherSize) + 1
    // mainMins = 0.1;
    // otherSecs = 4;
    // otherSize = 2;
    // app.launchApp("手机淘宝");
    waitDesc();
});
//保持脚本运行
setInterval(()=>{}, 1000);

//返回搜索页 
function backSearchView(){
    let 详情页返回 = className("android.widget.TextView").desc("返回").clickable();
    let 返回箭头 = 详情页返回.findOne(1000);
    if(返回箭头 != null){
        toastLog("点击左上角返回列表页");
        返回箭头.click();
        waitForActivity(searchActivityName);
    }

    if(currentActivity() != searchActivityName){
        // 返回搜索列表
        toastLog("返回列表,utils.back" );
        utils.back(searchActivityName);
    }
}

/**
 * 等待淘宝详细页
 */
function waitDesc(){
    while(true){
        sleep(2000);
        if(!window.switch.checked){
            sleep(3000);
            continue;
        }
        cur++;
        if(cur <= total){
        //浏览货比商品
            if(cur > 1){
                toastLog("等待列表页");
                waitForActivity(searchActivityName);
                sleep(3000);
                toastLog("获取到列表页");
                //切换展示模式com.taobao.taobao:id/styleBtn desc列表模式 到 大图模式
                if(cur == 2){
                    //防止按钮被遮盖
                    swipe(width/2 + random(-11,22), height/3,width/2+random(-11,22), height/3 + 120, 500);
                    toastLog("搜索列表模式按钮中");
                    var mode = id("com.taobao.taobao:id/styleBtn").findOne(1000);
                    if(mode != null){
                        var modeDesc = mode.desc();
                        toastLog("展示模式为："+ modeDesc);
                        if(modeDesc == '列表模式'){
                            utils.click(mode);
                            toastLog("展示模式切换为："+ mode.desc());
                        }
                    }
                    
                   
                }
                clickOther();
            }
            viewDesc();
            backSearchView();
            
            toastLog("剩余"+(total - cur));
            if(total == cur){
                toastLog("浏览货比商品全部结束");
            }
        }
        

        //最后回到列表页 
        if(total == cur){
            finish();
        }
        
    }
}


/**
 * -1  0：宝贝 1：评价 2：详情 3：推荐
 */
function navIndex(){
    var sel = id("ll_nav_tab_container");
    if(sel.exists()){
        var list = sel.findOne().children();
        for(var i = 0;i < list.size();i++){
            if(list.get(i).find(className("android.view.View")).nonEmpty()){
                return i;
            }
        }
    }
    return -1;
 }

var start = 0;
function viewDesc(time,speed){
    toastLog("等待商品详细页");
    waitForActivity(descActivityName);
    // sleep(2500);
    toastLog("商品详细页加载完成");
    var down = true;
    var end = new Date().getTime() + (time || cur==1?(mainMins*60*1000):(otherSecs*1000));
    speed = speed || 800;
    toastLog("浏览详细页开始");
    waitForActivity(descActivityName);

    var ms;
    var now,last;
    while(currentActivity() == descActivityName && (ms = end - new Date().getTime()) > 0){
        now = parseInt(ms/1000);
        if(now > 0 && (!last || now < last)){
            toastLog(utils.formatStr("剩余%s秒",now));
        }
        last = now;
       var index = navIndex();
       if(index < 2){
           down = true;
       }else if(index > 2){
           down = false;
       }
        if(down){
            swipe(width/2 + random(-11,22), 4*height/5+random(-11,22), width/2+random(-11,22), height/4+random(-11,22), speed + random(-11,31));
        }else{
            swipe(width/2 +random(-11,22), height/4+random(-11,22), width/2 +random(-11,22), 4*height/5+random(-11,22), speed + random(-11,31));
        }
        sleep(speed+random(-11,11));
    }
    if(end <= new Date().getTime()){
        toastLog("浏览详细页结束");
    }else{
        toastLog("浏览详细页异常结束,重新开始");
        viewDesc(time,speed);
    }  
    
}


function clickOther(){
    var aaa = id("com.taobao.taobao:id/libsf_srp_header_list_recycler");
    aaa.waitFor();
    scrollDownSearchView();
    var list = aaa.findOne().find(depth(14));
    
    var size = list.size();
    var index=0;
    var heights = [];
    var item;
    list.each(function(obj){
        if(item == null){
            var height = obj.bounds().height();
            if(heights.find(h => h==height) != null){
                if(index > 1 && index < size - 1){
                    item = obj;
                }  
            }else{
                heights.push(height);
            }
        }
        index++;
    })
    
    if(item == null){
        item = list.get(size -2);
    }
    utils.click(item);
    
}

function toastLog(message) {
    log(message);
    var myDate = new Date();
    ui.run(() => {
        w.WZ.setText(myDate.getHours() + "时" + myDate.getMinutes() + "分" + myDate.getSeconds() + "秒：" + message + "\n" + w.WZ.getText());
        return true;
    });
}

function scrollUpSearchView(){
    swipe(width/2 + random(-11,22), height/3,width/2+random(-11,22), height*7/8, 500);
    sleep(1500);
}

function scrollDownSearchView(){
    swipe(width/2 + random(-11,22), height*7/8, width/2+random(-11,22), height/3, 500);
    sleep(1500);
}